import * as React from 'react';
import { isWeixin } from 'user/services/weixinService';
import { ADMIN_APP } from 'share/common';
export { siteMap } from 'user/siteMap';
export { formatDate } from 'share/common';
import * as chitu from "maishu-chitu";
import lessc = require('lessc');
import { MemberService } from './services/memberService';

// export function formatDate(date: Date | string) {
//     if (typeof date == 'string')
//         return date;

//     let d = date as Date;
//     return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()} ${d.getHours() + 1}:${d.getMinutes()}`;
// }

export function subscribe<T>(component: React.Component<any, any>, item: chitu.ValueStore<T>, callback: (value: T) => void) {
    let func = item.add(callback);
    let componentWillUnmount = (component as any).componentWillUnmount as () => void;
    (component as any).componentWillUnmount = function () {
        item.remove(func);
        componentWillUnmount();
    }
}

//============================================================
// ui
export function defaultNavBar(element: HTMLElement,
    options?: { title?: string, right?: JSX.Element, showBackButton?: boolean }, back?: () => void);
export function defaultNavBar(elementPage: chitu.Page,
    options?: { title?: string, right?: JSX.Element, showBackButton?: boolean });
export function defaultNavBar(elementPage: chitu.Page | HTMLElement,
    options?: { title?: string, right?: JSX.Element, showBackButton?: boolean }, back?: () => void) {
    //=============================
    // window[ADMIN_APP] 表明为设计时
    if (window[ADMIN_APP]) {
        return null;
    }
    //=============================

    let element: HTMLElement;
    if ((elementPage as chitu.Page).element != null) {
        element = (elementPage as chitu.Page).element;
        back = () => ((elementPage as chitu.Page).app as chitu.Application).back();
    }
    else {
        element = elementPage as HTMLElement;
        if (back == null)
            throw new Error("back function can not null.")
    }


    if (isWeixin) {
        return weixinNavheader(element, options);
    }

    // document.title = options.title || "";
    options = options || {};
    let title = options.title || '';
    let className = element.className;
    if (className.indexOf("topbar-padding") < 0)
        element.className = className + ' topbar-padding';

    return (
        <nav className="bg-primary">
            <div className="pull-left" style={{ padding: 0, width: 60 }}>
                {options.showBackButton == false ?
                    <span dangerouslySetInnerHTML={{ __html: "&nbsp;" }}></span> :
                    <button name="back-button" className="left-button" style={{ opacity: 1 }} onClick={() => back()}>
                        <i className="icon-chevron-left"></i>
                    </button>
                }
                {/* {options.left} */}
            </div>
            <div className="pull-right" style={{ padding: 0, width: 60 }}>
                {options.right ? options.right :
                    <span dangerouslySetInnerHTML={{ __html: "&nbsp;" }}></span>}
            </div>
            <div className="" style={{ padding: 0 }}>
                <h4>
                    {title}
                </h4>
            </div>
        </nav>
    );
}

function weixinNavheader(element: HTMLElement, options?: { title?: string, right?: JSX.Element, left?: JSX.Element });
function weixinNavheader(elementPage: chitu.Page, options?: { title?: string, right?: JSX.Element, left?: JSX.Element })
function weixinNavheader(elementPage: any, options?: { title?: string, right?: JSX.Element, left?: JSX.Element }) {

    let element: HTMLElement;
    if ((elementPage as chitu.Page).element != null) {
        element = (elementPage as chitu.Page).element;
    }
    else {
        element = elementPage;
    }

    document.title = options.title || "";
    if (options.left == null && options.right == null)
        return null;

    let className = element.className;
    if (className.indexOf("topbar-padding") < 0)
        element.className = className + ' topbar-padding';

    return (
        <nav>
            <div className="col-xs-3" style={{ padding: 0 }}>
                {options.left}
            </div>
            <div className="col-xs-6" style={{ padding: 0 }}>

            </div>
            <div className="col-xs-3" style={{ padding: 0 }}>
                {options.right ? (options.right) : null}
            </div>
        </nav>
    );
}

export function loadCSS(pageName: string) {
    let path = pageName.split('_').join('/');
    requirejs([`less!user/modules/${path}`])
}

export function showLoading(page: chitu.Page) {
    let loadingView = page.element.querySelector('section.loading') as HTMLElement;
    if (loadingView == null) {
        loadingView = document.createElement('section');
        page.element.appendChild(loadingView);
    }
    else {
        loadingView.style.removeProperty('display');
    }

    loadingView.className = 'loading';
    loadingView.innerHTML = "数据正在加载中...";
    loadingView.style.textAlign = "center";
    loadingView.style.fontWeight = 'blod';
}

export function hideLoading(page: chitu.Page) {
    let loadingView = page.element.querySelector('section.loading') as HTMLElement;
    if (loadingView != null) {
        loadingView.style.display = 'none';
    }
}

export async function loadPageLess(pageName: string) {
    debugger
    let style = document.head.querySelector(`style[name="${pageName}"]`) as HTMLStyleElement;
    if (style) {
        return;
    }

    style = document.createElement('style');
    style.type = 'text/css';
    style.setAttribute('name', pageName);
    document.head.appendChild(style);

    let path = pageName.split('_').join('/');
    // let color = await this.styleColor();

    let member = new MemberService();
    let store = await member.store();
    let color = store.Style;
    debugger
    let lessText = `@import "../user/modules/${path}";`;
    if (color != 'default') {
        lessText = lessText + `@import "../components/style/colors/${color}.less";`;
    }

    let parser = new lessc.Parser(window['less']);
    parser.parse(lessText, (err, tree) => {
        if (err) {
            console.error(err);
            return;
        }

        style.innerHTML = tree.toCSS();
    })
}


